package com.hydra.gateway.listener;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.hydra.gateway.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cloud.loadbalancer.cache.DefaultLoadBalancerCacheManager;
import org.springframework.cloud.loadbalancer.cache.LoadBalancerCacheManager;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collection;

@Slf4j
@Component
public class GatewayNacosServerStatusListener extends Subscriber<InstancesChangeEvent> {

    private CacheManager cacheManager;

    @PostConstruct
    public void init() {
        log.info("订阅 nacos 服务");
        // 注册当前自定义的订阅者以获取通知
        NotifyCenter.registerSubscriber(this);
    }

    /**
     * Event callback.
     * @param event {@link Event}
     */
    @Override
    public void onEvent(InstancesChangeEvent event) {
        String serviceName = event.getServiceName();
        log.info("监听到服务上下线: {}", serviceName);
        // 使用 dubbo 时包含 rpc 服务类会注册以 providers: 或者 consumers: 开头的服务
        // 由于不是正式的服务, 这里需要进行排除, 如果未使用 dubbo 则不需要该处理
        if (serviceName.contains(":")) {
            return;
        }
        // serviceName 格式为 groupName@@name
        String split = Constants.SERVICE_INFO_SPLITER;
        if (serviceName.contains(split)) {
            serviceName = serviceName.substring(serviceName.indexOf(split) + split.length());
        }
        log.info("刷新 ribbon 服务实例：{}",serviceName);

        cacheManager = SpringUtils.getBean(LoadBalancerCacheManager.class);
        Collection<String> cacheNames = cacheManager.getCacheNames();
        for (String cacheName : cacheNames) {
            Cache cache = cacheManager.getCache(cacheName);
            if(cache != null){
                cache.evict(serviceName);
            }
        }

        log.info("刷新 ribbon 服务实例成功：{}",serviceName);
    }

    /**
     * Type of this subscriber's subscription.
     * @return Class which extends {@link Event}
     */
    @Override
    public Class<? extends Event> subscribeType() {
        return InstancesChangeEvent.class;
    }

}